from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding

# 读取私钥文件
def load_private_key(private_key_path):
    with open(private_key_path, "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,  # 如果私钥有保护，请在此处提供密码
            backend=default_backend()
        )
    return private_key

# 签名数据
def sign_data(private_key, data):
    signature = private_key.sign(
        data,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    return signature

def read_text_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        data = f.read().encode('utf-8')
    return data

# 主程序
if __name__ == "__main__":
    private_key_path = r'F:\project\30_BE12\BAIC_BE12_CODE\baic_be12_code\data\pub_dev.pem'
    data = read_text_file(r'F:\project\30_BE12\SW\BJEV_BE12_S010003_3.1.0.12_20241009\BE12_hex\New 0.txt')


    # 加载私钥
    private_key = load_private_key(private_key_path)
    
    # 签名数据
    signature = sign_data(private_key, data)
    
    print("签名结果:", signature.hex())
